package com.project.yunshitong;

import static android.content.ContentValues.TAG;
import static com.project.yunshitong.Utils.getAppVersionName;
import static com.project.yunshitong.Utils.getToast;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.project.yunshitong.bean.DepartmentBean;
import com.project.yunshitong.bean.GoodsInfo;
import com.project.yunshitong.bean.TypeBean;
import com.project.yunshitong.utils.ACache;
import com.project.yunshitong.utils.ExcelUtil;
import com.project.yunshitong.utils.FileUtils;
import com.project.yunshitong.utils.LoadingDialog;
import com.project.yunshitong.utils.MySQLiteOpenHelper;
import com.project.yunshitong.utils.ThreadPoolManager;

import org.apache.http.util.EncodingUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tvVer;
    private Button chooseFile;
    private TextView tvChooseFile;
    private Context context;
    private LinearLayout llImport;
    private LinearLayout llInventory;
    private LinearLayout llExport;
    private Intent intent;
    private LoadingDialog loading;
    private MySQLiteOpenHelper dbHelper1;
    private SQLiteDatabase sqliteDatabase1;
    private SQLiteDatabase sqliteDatabase4;

    private ACache aCache;
    private LinearLayout llScan;
    private int maxProgress = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    loading.show();
                    break;
            }
        }
    };
    private LinearLayout llExportExcel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        dbHelper1 = new MySQLiteOpenHelper(this, "goods_info");
        sqliteDatabase1 = dbHelper1.getWritableDatabase();
        sqliteDatabase4 = dbHelper1.getReadableDatabase();
        context = this;
        aCache = ACache.get(context);
        initView();
    }

    private void initView() {
        tvVer = findViewById(R.id.tvVer);
        chooseFile = findViewById(R.id.chooseFile);
        chooseFile.setOnClickListener(this);
        tvChooseFile = findViewById(R.id.tvChooseFile);
        llImport = findViewById(R.id.llImport);
        llInventory = findViewById(R.id.llInventory);
        llExport = findViewById(R.id.llExport);
        llImport.setOnClickListener(this);
        llInventory.setOnClickListener(this);
        llExport.setOnClickListener(this);
        llScan = findViewById(R.id.llScan);
        llScan.setOnClickListener(this);
        tvVer.setText("当前版本：" + getAppVersionName(context));
        llExportExcel = findViewById(R.id.llExportExcel);
        llExportExcel.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.chooseFile:
//                requestPermission();
//                try {
//                    chooseFile();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                break;
            case R.id.llImport:
                loading = new LoadingDialog(this, "正在处理数据", 1);
                loading.setCancelable(false);
//                CrashReport.testJavaCrash();
                requestPermission();
                try {
                    chooseFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.llInventory:
                intent = new Intent(context, InventoryActivity.class);
                startActivity(intent);
                break;
            case R.id.llExport:
                loading = new LoadingDialog(this, "正在处理数据", 2);
                loading.setCancelable(false);
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("导出盘点")
                        .setMessage("确定要导出盘点结果数据吗")
                        .setNegativeButton("取消", (dialog, which) -> {
                            dialog.dismiss();

                        })
                        .setPositiveButton("确定", (dialogInterface, i) -> {
                            loading.show();
                            ThreadPoolManager.getInstance().executeTask(new Runnable() {

                                @Override
                                public void run() {

                                    List<GoodsInfo> beanList = new ArrayList<>();
                                    sqliteDatabase4.beginTransaction();
                                    Cursor cursor;
                                    cursor = sqliteDatabase4.query("goods", null, "state=? or state=? or" +
                                                    " state=? or state=?",
                                            new String[]{"0", "1", "3", "4"},
                                            null, null, "id asc");
                                    beanList.clear();
                                    while (cursor.moveToNext()) {
                                        @SuppressLint("Range") String json = cursor.getString(cursor.getColumnIndex("json"));
                                        GoodsInfo goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
                                        beanList.add(goodsInfo);
                                    }
                                    maxProgress = beanList.size();
                                    sqliteDatabase4.setTransactionSuccessful();
                                    sqliteDatabase4.endTransaction();
                                    ExcelUtil.writeTxtFreq(context, beanList);
                                    runOnUiThread(() -> {
                                        loading.dismiss();
                                        getToast(context, "导出成功，共导出" + beanList.size() + "条数据");
                                    });
                                }
                            });
                        })
                        .create()
                        .show();
                break;

            case R.id.llExportExcel:
                loading = new LoadingDialog(this, "正在处理数据", 2);
                loading.setCancelable(false);
                AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
                builder1.setTitle("导出盘点")
                        .setMessage("确定要导出盘点结果数据到EXCEL中吗")
                        .setNegativeButton("取消", (dialog, which) -> {
                            dialog.dismiss();

                        })
                        .setPositiveButton("确定", (dialogInterface, i) -> {
                            loading.show();
                            ThreadPoolManager.getInstance().executeTask(new Runnable() {

                                @Override
                                public void run() {

//                                    String[] colName = {"名字1","名字2","名字3","名字4","名字5","名字6","名字7"};
//                                    ExcelUtil.initExcel(context, "导出数据",colName);
                                    List<GoodsInfo> beanList = new ArrayList<>();
                                    sqliteDatabase4.beginTransaction();
                                    Cursor cursor;
                                    cursor = sqliteDatabase4.query("goods", null, "state=? or state=? or" +
                                                    " state=? or state=?",
                                            new String[]{"0", "1", "3", "4"},
                                            null, null, "id asc");
                                    beanList.clear();
                                    while (cursor.moveToNext()) {
                                        @SuppressLint("Range") String json = cursor.getString(cursor.getColumnIndex("json"));
                                        GoodsInfo goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
                                        beanList.add(goodsInfo);
                                    }
                                    Cursor cursor1;
                                    HashMap<String,String> departmentList = new HashMap<>();
                                    cursor1 = sqliteDatabase4.query("department", null, null, null,
                                            null, null, null);
                                    departmentList.clear();
                                    while (cursor1.moveToNext()) {
                                        @SuppressLint("Range") String name = cursor1.getString(cursor1.getColumnIndex("name"));
//                                        @SuppressLint("Range") String superior = cursor1.getString(cursor1.getColumnIndex("superior"));
                                        @SuppressLint("Range") String departId = cursor1.getString(cursor1.getColumnIndex("departId"));
//                                        DepartmentBean departmentBean = new DepartmentBean(departId, superior, name);
//            Log.e(TAG, "initData: 获取的数据=====" + departmentBean);
                                        departmentList.put(departId,name);
                                    }
                                    maxProgress = beanList.size();
                                    sqliteDatabase4.setTransactionSuccessful();
                                    sqliteDatabase4.endTransaction();
                                    ExcelUtil.writeTxtFreqExcel(context,beanList,departmentList);
                                    runOnUiThread(() -> {
                                        loading.dismiss();
                                        getToast(context, "导出成功，共导出" + beanList.size() + "条数据");
                                    });
                                }
                            });
                        })
                        .create()
                        .show();
                break;
            case R.id.llScan:
                intent = new Intent(context, ScanActivity.class);
                startActivity(intent);
                break;
        }
    }

    /*获取权限*/
    private void requestPermission() {
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 没文件管理权限时申请权限
            if (!Environment.isExternalStorageManager()) {
//                isSetWallpaper = true;
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
                return;
            }
        }
        if (permissionList.size() > 0) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(this, permissions, 1);
        } else {
//            Log.e(TAG, "requestPermission: 所有权限获取成功");
//            openCamera(getActivity());
        }
    }

    private void chooseFile() throws IOException {
//        String folderPath = "/storage/emulated/0/项目/";
//        File folder = new File(folderPath);
//        if (folder.exists()) {
//            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.addCategory(Intent.CATEGORY_DEFAULT);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.setDataAndType(FileProvider.getUriForFile(context,
//                    context.getApplicationContext().getPackageName() + ".fileProvider",folder), "*/*");
//            try {
//            startActivityForResult(Intent.createChooser(intent, "选择文件"), 100);
////            startActivity(Intent.createChooser(intent,"选择浏览工具"));
//            } catch (ActivityNotFoundException e) {
//                e.printStackTrace();
//            }
//        }else{
//            folder.mkdirs();
////            File folder = new File(path);
//            if(null==folder || !folder.exists()){
//                return;
//            }
//            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.addCategory(Intent.CATEGORY_DEFAULT);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.setDataAndType(FileProvider.getUriForFile(context,
//                    context.getApplicationContext().getPackageName() + ".fileProvider",folder), "*/*");
//            try {
//            startActivityForResult(Intent.createChooser(intent, "选择文件"), 100);
////            startActivity(Intent.createChooser(intent,"选择浏览工具"));
//            } catch (ActivityNotFoundException e) {
//                e.printStackTrace();
//            }
//        }


        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "选择文件"), 100);
        } catch (ActivityNotFoundException ex) {
            getToast(this, "亲，木有文件管理器啊-_-!!");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (resultCode != Activity.RESULT_OK) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        String startNum = "20";
        if (requestCode == 100) {
            loading.show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Uri uri = data.getData();
                    Log.i(TAG, "------->" + uri.getPath());
                    try {
                        //dis.setText(readFileSdcardFile(FILE_NAME));
//                        String path = Uri2Path(context, uri);
                        String path = FileUtils.getFilePathFromUri(MainActivity.this, uri);
                        Log.e(TAG, "run: path==========" + path);
                        if (path == null) {
//                            Toast.makeText(this, "文件路径: " + path, Toast.LENGTH_LONG).show();
//                        } else {
//                            Toast.makeText(this, "无法获取文件路径", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (!path.contains(".dat")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    loading.dismiss();
                                    getToast(context, "请选择.dat文件");
                                }
                            });
                            return;
                        }
                        String fileInfo = readFileSdcardFile(path);
                        aCache.put("info", path);
                        aCache.put("name", path.substring(path.lastIndexOf("/"), path.lastIndexOf(".")));
                        fileInfo.replace("      ", "\t");
                        sqliteDatabase1.delete("department", null, null);
                        String department = fileInfo.substring(fileInfo.indexOf("#CDLIST=") + 8, fileInfo.indexOf(startNum)).trim();
                        List<String> departmentList = Arrays.asList(department.split("\t"));
                        Log.e(TAG, "run: departmentList.size()=====" + departmentList.size());
//                Log.e(TAG, "run: department====="+department );
                        boolean Rounding = departmentList.size() % 3 == 0;
                        DepartmentBean departmentBean = null;
                        for (int size = 0; size < departmentList.size(); size++) {
//                            Log.e(TAG, "run: departmentList====" + departmentList.get(size));
//                            if (size == departmentList.size() - 1) {
                            if (Rounding) {
                                if (size % 3 == 0) {
                                    departmentBean = new DepartmentBean(departmentList.get(size), departmentList.get(size + 1), departmentList.get(size + 2));
                                } else {
                                    departmentBean = null;
                                }
                            } else {
                                if (size == departmentList.size() - 1) {
                                    departmentBean = new DepartmentBean("", "", departmentList.get(size));
                                    break;
                                }
                            }
//                            } else {
//
//                            }
//                            Log.e(TAG, "run: 导入的数据====" + departmentBean);
                            if (departmentBean != null) {
                                sqliteDatabase1.beginTransaction();
                                ContentValues values = new ContentValues();
                                values.put("name", departmentBean.getDepartName());
                                values.put("superior", departmentBean.getDepartState());
                                values.put("departId", departmentBean.getDepartId());
                                long status1 = sqliteDatabase1.insert("department", null, values);
                                sqliteDatabase1.setTransactionSuccessful();
                                sqliteDatabase1.endTransaction();
                            }
                        }
                        String msg = fileInfo.substring(fileInfo.indexOf(startNum) - 2, fileInfo.indexOf(startNum));
//                        Log.e(TAG, "run: msg========="+msg );
                        if ("IT".equals(msg)) {
                            fileInfo = fileInfo.substring(fileInfo.indexOf(startNum) - 2);
                        } else {
                            fileInfo = fileInfo.substring(fileInfo.indexOf(startNum));
                        }
//                Log.e(TAG, "run: fileInfo.length()======="+fileInfo);
//                tvChooseFile.setText(fileInfo);
                        List<String> list = Arrays.asList(fileInfo.split("\n"));
                        sqliteDatabase1.delete("goods", null, null);
//                Log.e(TAG, "run: list.size()==========="+list.size() );
                        boolean infoFlag = true;
                        for (int a = 0; a < list.size(); a++) {
//                    Log.e(TAG, "run: list.get(a).trim()====="+list.get(a).trim() );
                            String[] infos = list.get(a).trim().split("\t");
//                    Log.e(TAG, "run: infos==========="+infos.length );
//                    for(int size = 0;size<infos.length;size++){
//                        Log.e(TAG, "run: infos[size]========"+infos[size] );
//                    }
                            List<String> info = new ArrayList<>(Arrays.asList(infos));
//                    Log.e(TAG, "onActivityResult: info.size()======" + info.size());
//                    for (int b = info.size() - 1; b >= 0; b--) {
//                        if (info.get(b).isEmpty()) {
//                            info.remove(b);
//                        } else {
//                            Log.e(TAG, "onActivityResult: 获取的内容是====" + info.get(b));
//                        }
//                    }
//                    if (info.size() < 11) {
//                        while (info.size() < 11) {
//                            info.add("");
//                        }
//                    }
                            if (info.size() > 11) {
//                        for(int s = 0;s<info.size();s++){
//                            Log.e(TAG, "run: 获取的数据是====="+s+"====="+info.get(s) );
//                        }
                                Log.e(TAG, "run: a==============" + a);
                                GoodsInfo goodsInfo = new GoodsInfo(info.get(0), info.get(1), info.get(2), info.get(3), info.get(4),
                                        info.get(5), info.get(6), info.get(7), info.get(8), info.get(9), info.get(10), info.get(11)
                                        , info.get(3), info.get(5));
                                String fixedNumber = "";
                                String code = goodsInfo.getCode();
                                if (code.length() > 2 && code.substring(0, 2).equalsIgnoreCase("IT")) {
                                    fixedNumber = "AA4E" + code.substring(2);
                                } else {
                                    fixedNumber = "AA" + code;
                                }
                                if (infoFlag) {
                                    infoFlag = false;
                                    if (code.length() > 2 && code.substring(0, 2).equals("IT")) {
                                        aCache.put("checkStatus", "1");
                                    } else {
                                        aCache.put("checkStatus", "2");
                                    }
                                }
                                if (fixedNumber.length() < 24) {
                                    for (int len = fixedNumber.length(); len < 24; len++) {
                                        fixedNumber = fixedNumber + "0";
                                    }
                                }
                                goodsInfo.setFixedNumber(fixedNumber);
//                                Utils.getList().add(goodsInfo);
                                sqliteDatabase1.beginTransaction();
                                ContentValues values = new ContentValues();
                                values.put("name", goodsInfo.getName());
                                values.put("number", goodsInfo.getCode());
                                values.put("fixedNumber", goodsInfo.getFixedNumber());
                                values.put("state", goodsInfo.getStatus());
                                values.put("deptid", goodsInfo.getDeptid());
                                values.put("oldDeptid", goodsInfo.getDeptid());
                                values.put("department", goodsInfo.getDepartment());
                                values.put("oldDepartment", goodsInfo.getDepartment());
                                values.put("time", "0");
                                values.put("json", new Gson().toJson(goodsInfo));
                                long status1 = sqliteDatabase1.insert("goods", null, values);
//                                Log.e(TAG, "run: ===========================" + goodsInfo);
                                sqliteDatabase1.setTransactionSuccessful();
//                        cursor1.close();
                                sqliteDatabase1.endTransaction();
//                        Log.e(TAG, "onClick: status1=========" + status1);
                            }
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                loading.dismiss();
                                AlertDialog alertDialog = new AlertDialog.Builder(context)
                                        .setTitle("提示")
                                        .setMessage("导入成功！")
                                        .setCancelable(false)
                                        .setPositiveButton("确定", (dialog, which) -> {
                                        }).create();
                                alertDialog.show();
//                                Toast toast = new Toast(context);
//                                getToast(context, "导入成功");
//                                toast.setText("导入成功");

//                                toast.setGravity(Gravity.CENTER,0,0);
//                                toast.show();
//                                Toast.makeText(MainActivity.this, "导入成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    public String readFileSdcardFile(String fileName) throws IOException {
        String res = "";
        try {
            FileInputStream fin = new FileInputStream(fileName);

            int length = fin.available();

            byte[] buffer = new byte[length];
            fin.read(buffer);

            res = EncodingUtils.getString(buffer, "GB2312");

            fin.close();
//            Log.e(TAG, "readFileSdcardFile: res============" + res.length());
        } catch (Exception e) {
            e.printStackTrace();
//            Log.e(TAG, "readFileSdcardFile: e============" + e.getLocalizedMessage());
        }
        return res;
    }


    public static String Uri2Path(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }

        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            return uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            String authority = uri.getAuthority();

            if (authority.startsWith("com.android.externalstorage")) {
                return Environment.getExternalStorageDirectory() + "/" + uri.getPath().split(":")[1];
            } else {
                String idStr = "";
                if (authority.equals("media")) {
                    idStr = uri.toString().substring(uri.toString().lastIndexOf('/') + 1);
                } else if (authority.startsWith("com.android.providers")) {
                    idStr = DocumentsContract.getDocumentId(uri).split(":")[1];
                }

                ContentResolver contentResolver = context.getContentResolver();
                Cursor cursor = contentResolver.query(MediaStore.Files.getContentUri("external"),
                        new String[]{MediaStore.Files.FileColumns.DATA},
                        "_id=?",
                        new String[]{idStr}, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    try {
                        int idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);

                        return cursor.getString(idx);
                    } catch (Exception e) {
                    } finally {
                        cursor.close();
                    }
                }
            }
        }
        return null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TypeBean event) {
//        Log.e(TAG, "onEventMainThread: ============="+event.toString() );
        if (event.getType() == 2) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loading.setProgress(event.getProgress(), maxProgress);
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}